<?php


namespace Logic;


use Cassandra\Varint;
use Config\mysql;

class LoginLogic
{
    public static function doLogin($pwd, $user)
    {
        $dbLink = mysql::mysql();
        $st = $dbLink->prepare('SELECT * FROM `tbUser` WHERE username=:user');
        $st->execute([':user' => $user]);
        $row = $st->fetch(\PDO::FETCH_ASSOC);/*读取从数据库获取的数据*/
        if (!$row) {
            return ['res' => -1, 'msg' => '用户不存在!' . $user];
        }
        if (!password_verify($pwd, $row['pwd'])) {
            return ['res' => -1, 'msg' => '密码错误!'];
        }
        $token = self::createToken();
        $row = self::cacheToken($token, $row);
        if (isset($row['res']) && $row['res'] != 0) {
            return ['res' => $row['res'], 'msg' => $row['msg'] ?? '系统繁忙，请稍后再试！'];
        }
        return [
            'res' => 0,
            'msg' => '登录成功!',
            'data' => [
                'token' => $token,
                'nickname' => htmlspecialchars($row['nickname']),
                'avator' => $row['avator'],
                'can_send_wishes' => $row['can_send_wishes'],
                'is_reveive_cdk' => $row['is_reveive_cdk'] ?? 0,
                'cdk' => $row['cdk'] ?? ''
            ]
        ];
    }


    /**
     * 登录缓存token到redis
     * @param $token
     * @param $row
     * @return array
     */
    public static function cacheToken($token, $row)
    {
        $redis = RedisClientLogic::getInstance();
        $row['can_send_wishes'] = 1; //1默认可以发送祝福语
        $wishId = $redis->hGet(USER_WISHES, $row['uid']);
        if ($wishId) {
            $row['can_send_wishes'] = 0;
        }
        $row['my_wish_id'] = $wishId ?? 0;
        $res = $redis->hMSet('token:' . $token, $row);
        $ex = $redis->expire('token:' . $token, 86400);
        if (!$res || !$ex) {
            return ['res' => -1, 'msg' => '系统繁忙，请稍后再试！' . $res . '--' . $ex];
        }
        return $row;
    }

    /**
     * 生成登录token
     * @return string
     * @throws \Exception
     */
    public static function createToken()
    {
        $length = 64;
        $string = '';
        while (($len = strlen($string)) < $length) {
            $size = $length - $len;

            $bytes = random_bytes($size);

            $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
        }
        $token = $string;
        return $token;
    }
}